import Vue from 'vue';
import iView from 'iview';
import Util from '../libs/util';
import VueRouter from 'vue-router';
import Cookies from 'js-cookie';
import {routers} from './router';

Vue.use(VueRouter);

// 路由配置
const RouterConfig = {
    // mode: 'history',
    routes: routers
};

export const router = new VueRouter(RouterConfig);

const getRouter = (arr, name) => {
    for (let value of arr) {
        if (value.name === name) {
            return true;
        }
    }
    return false;
};

const judgeAccess = (access, name, routers) => {
    for (let route of routers) {
        if (route.access && route.access.length) {
            if (route.name === name) {
                if (route.access.indexOf(access) === -1) {
                    return false;
                }
            }
            if (route.children && getRouter(route.children, name)) {
                if (route.access.indexOf(+access) === -1) {
                    return false;
                }
            }
        }
    }

    return true;
};

router.beforeEach((to, from, next) => {
    iView.LoadingBar.start();
    Util.title(to.meta.title);

    if (Cookies.get('user') && Cookies.get('access')) {
        if (!judgeAccess(Cookies.get('access'), to.name, routers)) {
            next({
                name: 'error_401'
            })
        }
    }

    if (!Cookies.get('user') && to.name !== 'login') {  // 判断是否已经登录且前往的页面不是登录页
        next({
            name: 'login'
        });
    } else if (Cookies.get('user') && to.name === 'login') {  // 判断是否已经登录且前往的是登录页
        // 特事特办
        if (from.name === 'home_index'){
            iView.LoadingBar.finish();
        }
        next({
            name: 'home_index'
        });
    } else {
        next();
    }
});

router.afterEach((to, from, next) => {
    iView.LoadingBar.finish();
    window.scrollTo(0, 0);
});
